package statement

import (
	"fmt"
	"gitee.com/KotlinToGo/xorm/builder"
	"gitee.com/KotlinToGo/xorm/internal/utils"
	"gitee.com/KotlinToGo/xorm/schema"
	"reflect"
	"strings"
)

var (
	ptrPkType  = reflect.TypeOf(&schema.PK{})
	pkType     = reflect.TypeOf(schema.PK{})
	stringType = reflect.TypeOf("")
	intType    = reflect.TypeOf(int64(0))
	uintType   = reflect.TypeOf(uint64(0))
)

// ErrIDConditionWithNoTable represents an error there is no reference table with an ID condition
type ErrIDConditionWithNoTable struct {
	ID schema.PK
}

func (err ErrIDConditionWithNoTable) Error() string {
	return fmt.Sprintf("ID condition %#v need reference table", err.ID)
}

// IsIDConditionWithNoTableErr return true if the err is ErrIDConditionWithNoTable
func IsIDConditionWithNoTableErr(err error) bool {
	_, ok := err.(ErrIDConditionWithNoTable)
	return ok
}

// Id generate "where id = ? " statement or for composite key "where key1 = ? and key2 = ?"
func (s *Statement) Id(id interface{}) *Statement {
	switch t := id.(type) {
	case *schema.PK:
		s.idParam = *t
	case schema.PK:
		s.idParam = t
	case string, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
		s.idParam = schema.PK{id}
	default:
		idValue := reflect.ValueOf(id)
		idType := idValue.Type()

		switch idType.Kind() {
		case reflect.String:
			s.idParam = schema.PK{idValue.Convert(stringType).Interface()}
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			s.idParam = schema.PK{idValue.Convert(intType).Interface()}
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
			s.idParam = schema.PK{idValue.Convert(uintType).Interface()}
		case reflect.Slice:
			if idType.ConvertibleTo(pkType) {
				s.idParam = idValue.Convert(pkType).Interface().(schema.PK)
			}
		case reflect.Ptr:
			if idType.ConvertibleTo(ptrPkType) {
				s.idParam = idValue.Convert(ptrPkType).Elem().Interface().(schema.PK)
			}
		}
	}

	if s.idParam == nil {
		s.LastError = fmt.Errorf("ID param %#v is not supported", id)
	}

	return s
}

// ProcessIDParam handles the process of id condition
func (s *Statement) ProcessIDParam() error {
	if s.idParam == nil {
		return nil
	}

	if s.RefTable == nil {
		return ErrIDConditionWithNoTable{s.idParam}
	}

	if len(s.RefTable.PrimaryKeys) != len(s.idParam) {
		return fmt.Errorf("ID condition is error, expect %d primarykeys, there are %d",
			len(s.RefTable.PrimaryKeys),
			len(s.idParam),
		)
	}

	for i, col := range s.RefTable.PKColumns() {
		var colName = s.colName(col, s.TableName())
		s.cond = s.cond.And(builder.Eq{colName: s.idParam[i]})
	}
	return nil
}

func (s *Statement) ConvertIDSQL(sqlStr string) string {
	if s.RefTable != nil {
		cols := s.RefTable.PKColumns()
		if len(cols) == 0 {
			return ""
		}

		colstrs := s.joinColumns(cols, false)
		sqls := utils.SplitNNoCase(sqlStr, " from ", 2)
		if len(sqls) != 2 {
			return ""
		}

		var top string
		pLimitN := s.LimitN
		if pLimitN != nil && s.dialect.URI().DBType == schema.Mssql {
			top = fmt.Sprintf("TOP %d ", *pLimitN)
		}

		newsql := fmt.Sprintf("SELECT %s%s FROM %v", top, colstrs, sqls[1])
		return newsql
	}
	return ""
}

func (s *Statement) ConvertUpdateSQL(sqlStr string) (string, string) {
	if s.RefTable == nil || len(s.RefTable.PrimaryKeys) != 1 {
		return "", ""
	}

	colstrs := s.joinColumns(s.RefTable.PKColumns(), true)
	sqls := utils.SplitNNoCase(sqlStr, "where", 2)
	if len(sqls) != 2 {
		if len(sqls) == 1 {
			return sqls[0], fmt.Sprintf("SELECT %v FROM %v",
				colstrs, s.quote(s.TableName()))
		}
		return "", ""
	}

	var whereStr = sqls[1]

	// TODO: for postgres only, if any other database?
	var paraStr string
	if s.dialect.URI().DBType == schema.Postgres {
		paraStr = "$"
	} else if s.dialect.URI().DBType == schema.Mssql {
		paraStr = ":"
	}

	if paraStr != "" {
		if strings.Contains(sqls[1], paraStr) {
			dollers := strings.Split(sqls[1], paraStr)
			whereStr = dollers[0]
			for i, c := range dollers[1:] {
				ccs := strings.SplitN(c, " ", 2)
				whereStr += fmt.Sprintf(paraStr+"%v %v", i+1, ccs[1])
			}
		}
	}

	return sqls[0], fmt.Sprintf("SELECT %v FROM %v WHERE %v",
		colstrs, s.quote(s.TableName()),
		whereStr)
}

